<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-11-05 11:39:43
 * @Last Modified time: 2023-02-15 12:33:15
 */
namespace frank\event;

use think\facade\Event;
use think\facade\Db;
use frank\services\CacheService;

/**
 * 初始化插件
 */
class InitAddon
{
    private $cache;

    ## 行为扩展的执行入口必须是run
    public function handle()
    {
        $this->cache = CacheService::instance();
        $this->initEvent();
    }
    /**
     * 初始化事件
     */
    private function InitEvent()
    {
        $cacheKey = "addon_event";
        $addonEvent = $this->cache->getTokenBucket($cacheKey);
        if(!defined("initroute_tag")) exit();
        if (empty($addonEvent)) {
            $addon  = Db::name('system_addon')->select()->ToArray();
            $listen_array = [];
            foreach ($addon as $k => $v) {
                if (file_exists(root_path().'addon/' . $v['addon_name'] . '/config/event.php') ) {
                    $addon_event = require_once root_path().'addon/' . $v['addon_name'] . '/config/event.php';
                    $listen = isset($addon_event['listen']) ? $addon_event['listen'] : [];
                    if (!empty($listen)) {
                        $listen_array[] = $listen;
                    }
                }

            }
            $this->cache->setTokenBucket($cacheKey, $listen_array);
        } else {
            $listen_array = $addonEvent;
        }
        if (!empty($listen_array)) {
            foreach ($listen_array as $k => $listen) {
                if (!empty($listen)) {
                    Event::listenEvents($listen);
                }
            }
        }
    }
}